<?php
namespace App\Controllers\Order;
use App\Models\Goods\Goods;
use App\Models\Order\Order;
use App\Models\Goods\GoodsAffiliate;
use App\Models\Coupons\Coupons;
use App\Models\Store\Store;
use App\Libs\Order\OrderList;
use \App\Libs\Helper\SmsHelper;
use App\Models\Experience\ExpOrder;

/**
*	获取订单详情
*/
class GetOrderDet extends \App\Libs\Base\BaseAction
{
    protected function beforeRun() {
        parent::beforeRun();
        $this->needLogin = TRUE;
    }
	
	public function execute(){
		$type = (int)$this->request->get('type');//1支付成功请求 2订单详情请求 3.订单是否使用状态查询 4.体验订单是否使用状态查询
		$user = $this->session->user;
		//获取信息
		$orderSn = $this->request->get('orderSn');//订单号
		
		if( $type == 4 ){
			//体验订单状态查询
			$order = ExpOrder::find( array(
				'id = :orderSn: and uid = '.$user->id,
				'bind'=>array( 'orderSn' => $orderSn )
			) );
			if( empty( $order ) ){
				return \App\Libs\Views\Json::view(1, '未查找到相关订单', Null );
			}
			return \App\Libs\Views\Json::view(0, '成功', ['status'=>$order->status] );
		}
		
		if( !empty( $orderSn ) ){
			//订单信息
			$order = Order::find( array(
				'order_sn = :orderSn: and uid = '.$user->id,
				'bind'=>array( 'orderSn' => $orderSn )
			) );
			if( empty( $order ) ){
				return \App\Libs\Views\Json::view(1, '未查找到相关订单', Null );
			}
			
			// 3.订单是否使用状态查询
			if( $type == 3 ){
				return \App\Libs\Views\Json::view(0, '成功', ['status'=>$order->status] );
			}
			
			//商品信息
			$goods = Goods::find( array(
				' id = :gid:',
				"columns"=>"goods_name",
				'bind'=>array( 'gid' => $order->gid )
			) );
			if( empty( $goods ) ){
				return \App\Libs\Views\Json::view(1, '未查找到订单相关商品信息', Null );
			}
			
			$info = ['goods_name'=>$goods->goods_name,'price'=>Goods::formatPrice($order->price),'orderSn'=>$orderSn,'qccode'=>DOMAIN_DOMAIN.'/index/qrcodeOrder?order_id='.$orderSn];
			
			//是否需要返回代金券信息
			if( $type == 1 ){
				if( !empty( $order->is_coupons ) ){
					$coupons = Coupons::find(array(
						' id = :cid: ',
						"columns"=>"title,full_price,price,type",
						'bind'=>array( 'cid' => $order->is_coupons )
					));
					if( !empty( $coupons ) ){
						$coupons = $coupons->toArray();
						$coupons['full_price'] = number_format( $coupons['full_price'] , 0 ,'','');
						$coupons['price'] = number_format( $coupons['price'] , 2 ,'.','');
					}else{
						$coupons = null;
					}
					$info['coupons'] = $coupons;
				}else{
					$info['coupons'] = null;
				}
				SmsHelper::instance()->send($user->phone, $user->username.','.$order->order_sn , \App\Libs\Base\Config::instance()->sms['tpl_order_id']);//发送订单成功短信
			}
			
			return \App\Libs\Views\Json::view(0, '成功', $info );
			
		}
		
		return \App\Libs\Views\Json::view(1, '传递参数有误，请检查参数', Null );
	}
}
